#include "mainwindow.h"
#include "storage.h"
#include <QDebug>

MainWindow::MainWindow(QWidget * parent):QMainWindow(parent),
m_ui(new Ui::MainWindow)
{
    m_ui->setupUi(this);
    m_model = new DataModel();
    connect(m_ui->saveButton, SIGNAL(clicked()), this, SLOT(save()));
    m_ui->listView->setModel(m_model);
    connect(m_ui->listView, SIGNAL(clicked(QModelIndex)), this, SLOT(updateData(QModelIndex)));
    connect(m_ui->listView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(saveLocal(const QModelIndex&, const QModelIndex&)));
    QModelIndex index = m_model->index(0, 0);
    m_ui->listView->selectionModel()->select(index, QItemSelectionModel::Select);
    updateData(index);
}

void MainWindow::save() {
    saveLocal(QModelIndex(), m_cur_index);
    m_model->saveData();
}

void MainWindow::updateData(QModelIndex index) {
    if (index.isValid()) {
        m_cur_index = index;
        Person person = m_model->getPerson(index);
        m_ui->firstNameEdit->setText(person.name);
        m_ui->lastNameEdit->setText(person.lastname);
        m_ui->phoneEdit->setText(person.phone);
        m_ui->emailEdit->setText(person.email);
        m_ui->notesEdit->clear();
        m_ui->notesEdit->appendPlainText(person.notes);
    }
}

void MainWindow::saveLocal(const QModelIndex & current, const QModelIndex & previous) {
    QString name = m_ui->firstNameEdit->text();
    QString lastname = m_ui->lastNameEdit->text();
    QString phone = m_ui->phoneEdit->text();
    QString email = m_ui->emailEdit->text();
    QString notes = m_ui->notesEdit->toPlainText();
    m_model->saveLocal(previous, name, lastname, phone, email, notes);
}
